{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "91707ee6",
   "metadata": {},
   "source": [
    "# 情感分析：使用循环神经网络\n",
    ":label:`sec_sentiment_rnn`\n",
    "\n",
    "与词相似度和类比任务一样，我们也可以将预先训练的词向量应用于情感分析。由于 :numref:`sec_sentiment`中的IMDb评论数据集不是很大，使用在大规模语料库上预训练的文本表示可以减少模型的过拟合。作为 :numref:`fig_nlp-map-sa-rnn`中所示的具体示例，我们将使用预训练的GloVe模型来表示每个词元，并将这些词元表示送入多层双向循环神经网络以获得文本序列表示，该文本序列表示将被转换为情感分析输出 :cite:`Maas.Daly.Pham.ea.2011`。对于相同的下游应用，我们稍后将考虑不同的架构选择。\n",
    "\n",
    "![将GloVe送入基于循环神经网络的架构，用于情感分析](../img/nlp-map-sa-rnn.svg)\n",
    ":label:`fig_nlp-map-sa-rnn`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d688acc1",
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "sys.path.append('..')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "201e0fb1",
   "metadata": {},
   "outputs": [],
   "source": [
    "from d2l import mindspore as d2l\n",
    "from mindspore import nn, ops, Tensor\n",
    "from mindspore import dtype as mstype\n",
    "from mindspore.common import initializer as weight_init\n",
    "\n",
    "batch_size = 64\n",
    "train_iter, test_iter, vocab = d2l.load_data_imdb(batch_size)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d4b6ec0f",
   "metadata": {},
   "source": [
    "## 使用循环神经网络表示单个文本\n",
    "\n",
    "在文本分类任务（如情感分析）中，可变长度的文本序列将被转换为固定长度的类别。在下面的`BiRNN`类中，虽然文本序列的每个词元经由嵌入层（`self.embedding`）获得其单独的预训练GloVe表示，但是整个序列由双向循环神经网络（`self.encoder`）编码。更具体地说，双向长短期记忆网络在初始和最终时间步的隐状态（在最后一层）被连结起来作为文本序列的表示。然后，通过一个具有两个输出（“积极”和“消极”）的全连接层（`self.decoder`），将此单一文本表示转换为输出类别。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "63b784fa",
   "metadata": {},
   "outputs": [],
   "source": [
    "class BiRNN(nn.Cell):\n",
    "    def __init__(self, vocab_size, embed_size, num_hiddens,\n",
    "                 num_layers, **kwargs):\n",
    "        super(BiRNN, self).__init__(**kwargs)\n",
    "        self.embedding = nn.Embedding(vocab_size, embed_size)\n",
    "        # 将bidirectional设置为True以获取双向循环神经网络\n",
    "        self.encoder = nn.LSTM(embed_size, num_hiddens, num_layers=num_layers,\n",
    "                                bidirectional=True)\n",
    "        self.decoder = nn.Dense(4 * num_hiddens, 2)\n",
    "\n",
    "    def constrtuct(self, inputs):\n",
    "        # inputs的形状是（批量大小，时间步数）\n",
    "        # 因为长短期记忆网络要求其输入的第一个维度是时间维，\n",
    "        # 所以在获得词元表示之前，输入会被转置。\n",
    "        # 输出形状为（时间步数，批量大小，词向量维度）\n",
    "        embeddings = self.embedding(inputs.T)\n",
    "        # 返回上一个隐藏层在不同时间步的隐状态，\n",
    "        # outputs的形状是（时间步数，批量大小，2*隐藏单元数）\n",
    "        outputs, _ = self.encoder(embeddings)\n",
    "        # 连结初始和最终时间步的隐状态，作为全连接层的输入，\n",
    "        # 其形状为（批量大小，4*隐藏单元数）\n",
    "        encoding = ops.cat((outputs[0], outputs[-1]), axis=1)\n",
    "        outs = self.decoder(encoding)\n",
    "        return outs"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fdd7d88d",
   "metadata": {},
   "source": [
    "让我们构造一个具有两个隐藏层的双向循环神经网络来表示单个文本以进行情感分析。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fbd576f6",
   "metadata": {},
   "outputs": [],
   "source": [
    "def init_weights(net):\n",
    "    init_normal = weight_init.XavierUniform()\n",
    "    for _, cell in net.cells_and_names():\n",
    "        if isinstance(cell, (nn.Dense, )):\n",
    "            cell.weight.set_data(weight_init.initializer(init_normal,\n",
    "                                                         cell.weight.shape,\n",
    "                                                         cell.weight.dtype))\n",
    "        if isinstance(cell, (nn.LSTM, )):\n",
    "            for name, param in cell.parameters_and_names():\n",
    "                if \"weight\" in name:\n",
    "                    weight = getattr(cell, name)\n",
    "                    weight.set_data(weight_init.initializer(init_normal, weight.shape,\n",
    "                    weight.dtype))                                                        \n",
    "            \n",
    "init_weights(net)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ca924e7e",
   "metadata": {},
   "source": [
    "## 加载预训练的词向量\n",
    "\n",
    "下面，我们为词表中的单词加载预训练的100维（需要与`embed_size`一致）的GloVe嵌入。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bb1acca9",
   "metadata": {},
   "outputs": [],
   "source": [
    "glove_embedding = d2l.TokenEmbedding('glove.6b.100d')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0bc252be",
   "metadata": {},
   "source": [
    "打印词表中所有词元向量的形状。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "685a2fd7",
   "metadata": {},
   "outputs": [],
   "source": [
    "embeds = glove_embedding[vocab.idx_to_token]\n",
    "embeds.shape"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9df67b66",
   "metadata": {},
   "source": [
    "我们使用这些预训练的词向量来表示评论中的词元，并且在训练期间不要更新这些向量。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ec007ddd",
   "metadata": {},
   "outputs": [],
   "source": [
    "net.embedding.embedding_table.set_data(d2l.tensor(embeds))\n",
    "net.embedding.embedding_table.requires_grad = False"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7ecdce84",
   "metadata": {},
   "source": [
    "## 训练和评估模型\n",
    "\n",
    "现在我们可以训练双向循环神经网络进行情感分析。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6f38c983",
   "metadata": {},
   "outputs": [],
   "source": [
    "lr, num_epochs = 0.01, 5\n",
    "trainer = nn.Adam(learning_rate=lr, params=net.trainable_params())\n",
    "loss = nn.CrossEntropyLoss(reduction=\"none\")\n",
    "d2l.train_ch13(net, train_iter, test_iter, loss, trainer, num_epochs)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a2d78ecd",
   "metadata": {},
   "source": [
    "我们定义以下函数来使用训练好的模型`net`预测文本序列的情感。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d23a35b0",
   "metadata": {},
   "outputs": [],
   "source": [
    "def predict_sentiment(net, vocab, sequence):\n",
    "    \"\"\"预测文本序列的情感\"\"\"\n",
    "    sequence = Tensor(vocab[sequence.split()], mstype.int32)\n",
    "    label = ops.argmax(net(sequence.reshape((1, -1))), axis=1)\n",
    "    return 'positive' if label == 1 else 'negative'"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9634250f",
   "metadata": {},
   "source": [
    "最后，让我们使用训练好的模型对两个简单的句子进行情感预测。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c6312d18",
   "metadata": {},
   "outputs": [],
   "source": [
    "predict_sentiment(net, vocab, 'this movie is so great')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "966141f9",
   "metadata": {},
   "outputs": [],
   "source": [
    "predict_sentiment(net, vocab, 'this movie is so bad')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "307a8586",
   "metadata": {},
   "source": [
    "## 小结\n",
    "\n",
    "* 预训练的词向量可以表示文本序列中的各个词元。\n",
    "* 双向循环神经网络可以表示文本序列。例如通过连结初始和最终时间步的隐状态，可以使用全连接的层将该单个文本表示转换为类别。\n",
    "\n",
    "## 练习\n",
    "\n",
    "1. 增加迭代轮数可以提高训练和测试的准确性吗？调优其他超参数怎么样？\n",
    "1. 使用较大的预训练词向量，例如300维的GloVe嵌入。它是否提高了分类精度？\n",
    "1. 是否可以通过spaCy词元化来提高分类精度？需要安装Spacy（`pip install spacy`）和英语语言包（`python -m spacy download en`）。在代码中，首先导入Spacy（`import spacy`）。然后，加载Spacy英语软件包（`spacy_en = spacy.load('en')`）。最后，定义函数`def tokenizer(text): return [tok.text for tok in spacy_en.tokenizer(text)]`并替换原来的`tokenizer`函数。请注意GloVe和spaCy中短语标记的不同形式。例如，短语标记“new york”在GloVe中的形式是“new-york”，而在spaCy词元化之后的形式是“new york”。\n",
    "\n",
    ":begin_tab:`mxnet`\n",
    "[Discussions](https://discuss.d2l.ai/t/5723)\n",
    ":end_tab:\n",
    "\n",
    ":begin_tab:`pytorch`\n",
    "[Discussions](https://discuss.d2l.ai/t/5724)\n",
    ":end_tab:\n",
    "\n",
    ":begin_tab:`paddle`\n",
    "[Discussions](https://discuss.d2l.ai/t/11826)\n",
    ":end_tab:"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
